package com.zcyr.util;

import com.zcyr.core.AbstractDatabaseEnvironmentManager;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@Component
public class SessionListener implements HttpSessionListener {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    AbstractDatabaseEnvironmentManager databaseEnvironmentManager;

    @SneakyThrows
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String environmentUUID = (String) session.getAttribute("environmentUUID");
        if (environmentUUID != null){
            databaseEnvironmentManager.releaseDatabaseEnvironment(environmentUUID);
        }
        HttpSessionListener.super.sessionDestroyed(se);
    }
}
